package com.bac.rentmap.web.controller.osmimport;

import com.bac.rentmap.manager.BuildingManager;
import com.bac.rentmap.manager.StreetManager;
import com.bac.rentmap.model.Building;
import com.bac.rentmap.model.Street;
import com.bac.rentmap.osm.BuildingsReader;
import com.bac.rentmap.osm.StreetsReader;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.mvc.AbstractController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 *
 * @author Ivan Holub
 */
public class ImportStreetsServiceController extends AbstractController {

    private StreetsReader streetsReader;

    private StreetManager streetManager;

    public void setStreetsReader(StreetsReader streetsReader) {
        this.streetsReader = streetsReader;
    }

    public void setStreetManager(StreetManager streetManager) {
        this.streetManager = streetManager;
    }
    
    protected ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

        String numberParam = httpServletRequest.getParameter("number");
        int number = Integer.valueOf(numberParam);

        List<Street> buildings = streetsReader.readStreets(getServletContext());

        int maxNumber = streetManager.getMaxNumber();

        int fromIndex = maxNumber;
        int toIndex = maxNumber + number;
        if (fromIndex < buildings.size()) {
            if (toIndex > buildings.size()) {
                toIndex = buildings.size();
            }
            buildings = buildings.subList(fromIndex, toIndex);

            streetManager.saveStreets(buildings);
        }

        maxNumber = streetManager.getMaxNumber();

        ModelAndView mav = new ModelAndView("admin/import/osm/importstreetsservice");
        mav.addObject("maxNumber", maxNumber);
        return mav;
    }
}